const express = require("express");
const router = express.Router();
const db = require("../models");
const verify = require("../tools/verifyToken");

router.get("/all", verify, (req, res) => {
  console.log(req.ip);
  db.Inventory.findAll({ include: ["Product", "Client"] })
    .then((inventories) => res.send(inventories))
    .catch((err) => {
      res.status(400).send(err.message);
    });
});

router.get("/:id", verify, (req, res) => {
  db.Inventory.findAll({
    where: {
      id: req.params.id,
    },
  })
    .then((inventory) => {
      res.send(inventory);
    })
    .catch((err) => {
      res.status(400).send(err.message);
    });
});

router.post("/add", verify, (req, res) => {
  const inventory = req.body;
  console.log(inventory);
  // if(!inventory.id)
  //     inventory.id = Math.floor(Math.random()*1000000+1)
  db.Inventory.create(inventory)
    .then((inventory) => {
      res.send(inventory);
    })
    .catch((err) => {
      res.status(400).send(err);
    });
});

router.post("/delete", verify, (req, res) => {
  db.Inventory.destroy({
    where: {
      id: req.body.id,
    },
  })
    .then((n) => {
      res.send({ deleted: n });
    })
    .catch((err) => {
      res.send(err);
    });
});

router.post("/edit", verify, (req, res) => {
  console.log(req.body);
  db.Inventory.update(req.body, {
    where: {
      id: req.body.id,
    },
  })
    .then((inventory) => {
      res.send(inventory);
    })
    .catch((err) => {
      res.send(err);
    });
});
module.exports = router;
